package com.yifeng.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import javax.servlet.http.Part;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.UUID;

public class AliOssUtil {
    private static String accessKeyId;
    private static String accessKeySecret;
    private static String bucketName;
    private static String endpoint;
    private static String region;

    // 从Properties中获取阿里云账号的AccessKeyId和AccessKeySecret
    static {
        Properties props = new Properties();
        InputStream is = AliOssUtil.class.getClassLoader().getResourceAsStream("oss.properties");
        try {
            props.load(is);
            accessKeyId = props.getProperty("oss.accessKeyId");
            accessKeySecret = props.getProperty("oss.accessKeySecret");
            bucketName = props.getProperty("oss.bucketName");
            endpoint = props.getProperty("oss.endpoint");
            region = props.getProperty("oss.region");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String upload(Part part) throws IOException {
        // 从 Part 获取原始文件名
        String fileName = part.getSubmittedFileName();
        // 生成新的唯一文件名
        String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));

        OSS ossClient = new OSSClientBuilder()
                .build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 直接使用 part.getInputStream() 作为内容源
            ossClient.putObject(bucketName, newFileName, part.getInputStream());
        } finally {
            ossClient.shutdown();
        }
        return "https://" + bucketName + "." + endpoint + "/" + newFileName;
    }
}
